import {
  ds
} from '../../../tools/data'
import {
  users
} from '../../../tools/users'
import {
  localData
} from '../../../tools/localData'
import {
  checkTool
} from '../../../tools/check'
import {
  ui
} from '../../../tools/ui'
import {
  pages
} from '../../../tools/pages'
import {
  dsFiles
} from '../../../tools/dsFiles'

const cloudPrefix = getApp().globalData.cloudPrefix

Page({
  data: {
    userInfo: {}, // user
    showUnbindConfirm: false,
    pickerOptions: [{
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
    cloudPrefix
  },
  onLoad() {
    const that = this
    that.init();
  },
  init() {
    this.fetchData();
  },
  async fetchData() {
    ui.loading()
    const that = this
    users.getUserInfo()
      .then(async userInfo => {
        that.updateUserInfo(userInfo)
        ui.loading(false)
        // console.log(userInfo)
      })

    // fetchPerson().then((personInfo) => {
    //   this.setData({
    //     personInfo,
    //     'personInfo.phoneNumber': phoneEncryption(personInfo.phoneNumber),
    //   });
    // });
  },
  onChooseAvatar(e) {
    // console.log(e)
    ui.loading()
    const that = this
    const url = e.detail.avatarUrl
    let userInfo = this.data.userInfo
    userInfo.personInfo = userInfo.personInfo || {}
    dsFiles.uploadFile(url, fileId => {
      dsFiles.insert2files(fileId, null, 'avatar')
      userInfo.personInfo.avatarUrl = fileId
      that.updateUserInfo(userInfo)
      that.saveUserInfo(userInfo)
      ui.loading(false)
    })
  },
  updateUserInfo(userInfo) {
    // localData.set('userinfo', userInfo)
    // console.log('update', userInfo)
    if (!userInfo._id) return
    this.setData({
      userInfo
    })
  },
  onRefresh() {
    const that = this
    ui.loading()
    ds.cloudGetByOpenid('users', res => {
      const userInfo = res.result.data[0]
      if (userInfo) that.updateUserInfo(userInfo)
      ui.loading(false)
    })
  },
  savePersonInfoClick() {
    const userInfo = this.data.userInfo
    if (!userInfo._id) return

    checkTool.check([{
      value: userInfo.email,
      regex: checkTool.CommonRegex.email,
      allowEmpty: true,
      title: '邮箱'
    }])

    ui.loading()
    this.saveUserInfo(userInfo, res => {
      ui.loading(false)
      ui.toast(res.result && res.result.errMsg.endsWith(":ok"), '', () => {
        pages.back()
      })
    })
  },
  saveUserInfo(userInfo, cb) {
    if (!userInfo._id) return
    ds.cloudUpdate('users', userInfo._id, userInfo, res => {
      if (cb) cb(res)
    })
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;

    switch (dataset.type) {
      case 'gender':
        ui.actionSheet(['男', '女', '保密'], res => {
          let userInfo = dataset.userinfo
          userInfo.personInfo = userInfo.personInfo || {}
          userInfo.personInfo.gender = res
          this.updateUserInfo(userInfo)
        })
        break;
        // case 'name':
        //   wx.navigateTo({
        //     url: `/pages/usercenter/name-edit/index?name=${nickName}`,
        //   });
        //   break;
        // case 'avatarUrl':
        //   this.toModifyAvatar();
        //   break;
      default: {
        break;
      }
    }
  },
  onValueChange(e) {
    const {
      type,
      userinfo
    } = e.currentTarget.dataset
    const {
      value
    } = e.detail

    if (!userinfo._id) return
    if (type == 'nickName') {
      userinfo.personInfo = userinfo.personInfo || {}
      userinfo.personInfo.nickName = value
    } else {
      userinfo[type] = value
    }

    this.updateUserInfo(userinfo)
  },
  getPhoneNumber(event) {
    const userInfo = event.currentTarget.dataset.userinfo
    users.getMobile(event, phoneNumber => {
      userInfo.phoneNumber = phoneNumber
      this.updateUserInfo(userInfo)
    })
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
      },
    );
  },
  async toModifyAvatar() {
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              resolve(path);
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      const tempUrlArr = tempFilePath.split('/');
      const tempFileName = tempUrlArr[tempUrlArr.length - 1];
      Toast({
        context: this,
        selector: '#t-toast',
        message: `已选择图片-${tempFileName}`,
        theme: 'success',
      });
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'fail',
      });
    }
  },
  deliFeeClick() {
    const {
      userInfo
    } = this.data
    const nickName = userInfo.personInfo?.nickName || ''
    wx.navigateTo({
      url: `/pages/usercenter/staff/deliveryFee/deliFee?staffId=${userInfo._id}&nickName=${nickName}`,
    })
  },
  deductFeeClick() {
    const {
      userInfo
    } = this.data
    const nickName = userInfo.personInfo?.nickName || ''
    wx.navigateTo({
      url: `/pages/usercenter/staff/deductFee/deductFee?staffId=${userInfo._id}&nickName=${nickName}`,
    })
  }
});